/*
This file is part of cdbnlib.

    cdbnlib is free software: you can redistribute it and/or modify it under
    the terms of the GNU Lesser General Public License as published by the Free
    Software Foundation, either version 3 of the License, or (at your option)
    any later version.

    cdbnlib is distributed in the hope that it will be useful, but WITHOUT ANY
    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
    more details.

    You should have received a copy of the GNU Lesser General Public License
    along with cdbnlib.  If not, see <http://www.gnu.org/licenses/>.
*/


#include "cdbnlib.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#define RANDUNIFORM (random()/(double)RAND_MAX)

/* This function implements the polar form of the Box-Muller
 * transformation for generating Gaussian pseudo-random numbers
 * given a source of uniform pseudo-random numbers
 *
 * source:
 * http://www.taygeta.com/random/gaussian.html
 */
void dl_get_box_muller_random_normal_2d(double *randn1, double *randn2, double scale)
{
	double x1, x2, w;
	do {
		x1 = 2.0 * RANDUNIFORM - 1.0;
		x2 = 2.0 * RANDUNIFORM - 1.0;
		w = x1*x1 + x2*x2;
	} while (w >= 1.0);
	w = sqrt((-2.0*log(w))/w)*scale;
	*randn1 = x1*w;
	*randn2 = x2*w;
}

